package com.yanfan.zutai.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.yanfan.common.constant.HttpStatus;
import com.yanfan.common.core.page.PageDomain;
import com.yanfan.common.core.page.TableDataInfo;
import com.yanfan.common.core.page.TableSupport;
import com.yanfan.iot.tdengine.config.TDengineDatabaseConfig;
import com.yanfan.iot.tdengine.dao.ZuTaiTDengineMapper;
import com.yanfan.zutai.domain.BDeviceHistoryData;
import com.yanfan.zutai.domain.BDeviceZtBind;
import com.yanfan.zutai.mapper.BDeviceHistoryDataMapper;
import com.yanfan.zutai.service.IBDeviceHistoryDataService;
import com.yanfan.zutai.util.DateUtilLocal;
import com.yanfan.zutai.util.Detect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * 设备实时数据Service业务层处理
 *
 * @author ruoyi
 * @date 2022-05-28
 */
@Service
public class BDeviceHistoryDataServiceImpl implements IBDeviceHistoryDataService {
    @Autowired
    private BDeviceHistoryDataMapper bDeviceHistoryDataMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired(required = false)
    private ZuTaiTDengineMapper zuTaiTDengineMapper;
    @Autowired
    private TDengineDatabaseConfig tDengineDatabaseConfig;

    /**
     * 查询设备实时数据
     *
     * @param id 设备实时数据主键
     * @return 设备实时数据
     */
    @Override
    public BDeviceHistoryData selectBDeviceHistoryDataById(Long id) {
        return bDeviceHistoryDataMapper.selectBDeviceHistoryDataById(id);
    }

    /**
     * 查询设备实时数据列表
     *
     * @param bDeviceHistoryData 设备实时数据
     * @return 设备实时数据
     */
    @Override
    public List<BDeviceHistoryData> selectBDeviceHistoryDataList(BDeviceHistoryData bDeviceHistoryData) {
        return bDeviceHistoryDataMapper.selectBDeviceHistoryDataList(bDeviceHistoryData);
    }

    /**
     * 新增设备实时数据
     *
     * @param bDeviceHistoryData 设备实时数据
     * @return 结果
     */
    @Override
    public int insertBDeviceHistoryData(BDeviceHistoryData bDeviceHistoryData) {
        Snowflake snowflake = IdUtil.getSnowflake(6, 2);
        long id = snowflake.nextId();
        bDeviceHistoryData.setId(id);
        return bDeviceHistoryDataMapper.insertBDeviceHistoryData(bDeviceHistoryData);
    }

    /**
     * 修改设备实时数据
     *
     * @param bDeviceHistoryData 设备实时数据
     * @return 结果
     */
    @Override
    public int updateBDeviceHistoryData(BDeviceHistoryData bDeviceHistoryData) {
        return bDeviceHistoryDataMapper.updateBDeviceHistoryData(bDeviceHistoryData);
    }

    /**
     * 批量删除设备实时数据
     *
     * @param ids 需要删除的设备实时数据主键
     * @return 结果
     */
    @Override
    public int deleteBDeviceHistoryDataByIds(Long[] ids) {
        return bDeviceHistoryDataMapper.deleteBDeviceHistoryDataByIds(ids);
    }

    /**
     * 删除设备实时数据信息
     *
     * @param id 设备实时数据主键
     * @return 结果
     */
    @Override
    public int deleteBDeviceHistoryDataById(Long id) {
        return bDeviceHistoryDataMapper.deleteBDeviceHistoryDataById(id);
    }

    @Override
    public TableDataInfo selectBDeviceHistoryDataTaosList(BDeviceHistoryData bDeviceHistoryData) {
        TableDataInfo rspData = new TableDataInfo();

        if (zuTaiTDengineMapper == null) {
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("TDengine数据库未启用");
            return rspData;
        }

        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        List<String> imeiList = new ArrayList<>();
        if (Detect.notEmpty(bDeviceHistoryData.getZtGuid())) {
            String ztSql = "select * from b_device_zt_bind where zt_guid=?";
            BeanPropertyRowMapper<BDeviceZtBind> bindBeanPropertyRowMapper = new BeanPropertyRowMapper<>(BDeviceZtBind.class);
            List<BDeviceZtBind> ztBinds = jdbcTemplate.query(ztSql, bindBeanPropertyRowMapper, bDeviceHistoryData.getZtGuid());
            for (int i = 0; i < ztBinds.size(); i++) {
                imeiList.add(ztBinds.get(i).getDeviceMac());
            }
            bDeviceHistoryData.setImeiList(imeiList);
        }
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer stringCountBuffer = new StringBuffer();
        // 多子表使用超级表查询
        if (imeiList.size() > 0) {
            stringBuffer.append("select id, dept_Id_strs as deptIdStrs, report_time as reportTime, device_imei as deviceImei, device_name as deviceName, param_name as paramName, param_field as paramField, param_value as paramValue, param_unit as paramUnit " +
                    " from `"+tDengineDatabaseConfig.getDbName()+"`.`b_device_history_data` where 1=1 ");
            stringCountBuffer.append("select count(1) from b_device_history_data where 1=1 ");
            String appendSql = "and device_imei in (";
            for (int i = 0; i < imeiList.size(); i++) {
                String imei = imeiList.get(i);
                appendSql += "'" + imei + "',";
            }
            appendSql = appendSql.substring(0, appendSql.length() - 1) + ")";
            stringBuffer.append(appendSql);
            stringCountBuffer.append(appendSql);
        } else if (Detect.notEmpty(bDeviceHistoryData.getDeviceImei())) {
            stringBuffer.append("select id,dept_Id_strs as deptIdStrs, report_time as reportTime, device_imei as deviceImei, device_name as deviceName, param_name as paramName, param_field as paramField, param_value as paramValue, param_unit as paramUnit from d" + bDeviceHistoryData.getDeviceImei() + " where 1=1 ");
            stringCountBuffer.append("select count(1) from d" + bDeviceHistoryData.getDeviceImei() + " where 1=1 ");
        } else {
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("参数校验失败");
            rspData.setRows(new ArrayList<>());
            rspData.setTotal(0);
            return rspData;
        }
        if (Detect.notEmpty(bDeviceHistoryData.getParamName())) {
            stringBuffer.append("and param_name='" + bDeviceHistoryData.getParamName() + "' ");
            stringCountBuffer.append("and param_name='" + bDeviceHistoryData.getParamName() + "' ");
        }
        if (Detect.notEmpty(bDeviceHistoryData.getBeginTime())) {
            Long timestamp = DateUtilLocal
                    .parseDate(bDeviceHistoryData.getBeginTime(), "yyyy-MM-dd HH:mm:ss")
                    .getTime();
            stringBuffer.append(" AND report_time >= " + timestamp);
            stringCountBuffer.append(" AND report_time >= " + timestamp);
        }
        if (Detect.notEmpty(bDeviceHistoryData.getEndTime())) {
            Long timestamp = DateUtilLocal.parseDate(bDeviceHistoryData.getEndTime(), "yyyy-MM-dd HH:mm:ss").getTime();
            stringBuffer.append(" AND report_time <= " + timestamp);
            stringCountBuffer.append(" AND report_time <= " + timestamp);
        }
        stringBuffer.append(" order by report_time desc");
        stringBuffer.append(" limit " + (pageNum - 1) * pageSize + "," + pageSize);
        BeanPropertyRowMapper<BDeviceHistoryData> bindBeanPropertyRowMapper = new BeanPropertyRowMapper<>(BDeviceHistoryData.class);
        // 因子表不一定存在，所以需要判断下
        try {
            List<BDeviceHistoryData> list = zuTaiTDengineMapper.selectBDeviceHistoryDataTaosList(stringBuffer.toString());
            String countSql = stringCountBuffer.toString();
            Long tableCount = zuTaiTDengineMapper.countBDeviceHistoryDataTaos(countSql);
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(list);
            rspData.setTotal(tableCount);
        } catch (UncategorizedSQLException exception) {
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("子表不存在");
            rspData.setRows(new ArrayList<>());
            rspData.setTotal(0);
        }
        return rspData;
    }
}
